app.controller('NotificationsController', NotificationsController);
app.controller('chatCtrl', chatCtrl);
app.controller('PatientSummaryController', PatientSummaryController);
//app.controller('ServiceSummaryController', ServiceSummaryController);
app.controller('DashboardSummaryController', DashboardSummaryController);

function NotificationsController($scope, $rootScope, $interval, $filter, $translate, RESTService, CS, $timeout, $sce, AuthService, $modal) {
    $scope.addFriend = {
        like: ''
        , count: 0
        , FriendsList: ''
        , pageNo: 1
        , pageSize: 10
        , thisPageSize: 0
        , selectPerNum: 2
    };

    var modalInstance;

    $scope.openFriendList = function () {
        $scope.addFriend.like = '';

        $scope.filterFriend();

        $scope.open({templateUrl: 'friendListModal.html', size: 'lg'});
    }

    $scope.openMedicalList = function () {
        // $scope.addFriend.like = '';

        RESTService.getResponse('/rest/user/getUsers?userRole=MedicalAdmin&pageNo=1&pageSize=99&like=').then(
            function(res){
                $scope.medicalList = res;
                // $scope.addFriend.thisPageSize = $scope.addFriend.count = $scope.addFriend.FriendsList.length;
            }
        );

        $scope.open({templateUrl: 'medicalListModal.html', size: 'lg'});
    }

    $scope.filterFriend = function () {
        RESTService.getResponse('/rest/userfriend/getNotFriendsCount?like=' + $scope.addFriend.like)
            .then(function (res) {
                $scope.addFriend.count = res[0].count;
            });

        RESTService.getResponse('/rest/userfriend/getNotFriends?like=' + $scope.addFriend.like + '&pageSize=' + $scope.addFriend.pageSize + '&pageNo=' + $scope.addFriend.pageNo)
            .then(function (res) {
                console.log(res);
                $scope.addFriend.FriendsList = res;
                $scope.addFriend.thisPageSize = $scope.addFriend.FriendsList.length;
            });
    }

    $scope.selectPage = function () {
        $scope.filterFriend();
    }
    //3 open modal
    $scope.open = function (attrs, model, toggle) {
        console.log(attrs, model, toggle);
        if (toggle == 'friendInfo' && model == null) {
            return
        }
        modalInstance = $modal.open(angular.extend({
            backdrop: "static",
            controller: "ModalInstanceCtrl",
            resolve: {
                items: function () {
                    return [Object(model)];
                }
            },
            scope: $scope
        }, attrs));
    };

    // test network
    var EventUtil = {
        addHandler: function (element, type, handler) {
            if (element.addEventListener) {
                element.addEventListener(type, handler, false);
            } else if (element.attachEvent) {
                element.attachEvent("on" + type, handler);
            } else {
                element["on" + type] = handler;
            }
        }
    };
    EventUtil.addHandler(window, "online", function () {
        // 建立WebSocket连接
        ws();
        console.log('system : online');
    });
    EventUtil.addHandler(window, "offline", function () {
        websocket = null;
        console.log('system : offline');
    });

    $scope.if_open_chat = false;
    $scope.notes = {
        count: 0
        , content: ''
        , list: []
    };

    $scope.taskSummary = '';
    $scope.currentUser = '';

    var timer = $interval(function () {
        $scope.loadNotesData();
        //此处添加一个心跳检测方法，用于探测消息服务器是否连接正常


    }, 1000 * 60);  //exec one time of 60 seconds

    //获取待办事项和未读消息条数小红点提示
    $scope.loadNotesData = function () {
        $scope.currentUser = $rootScope.currentUser;
        // console.log("1=============== NotificationsController $rootScope.currentUser = ", $rootScope.currentUser);
        var token = RESTService.getAccess_Token();
        // console.log("2=============== NotificationsController token = ", token);
        if (!token) {
            // console.log("3=============== NotificationsController token = ", token);
            $interval.cancel(timer);
            return;
        }

        //小红点待办事项总条数提示
        RESTService.getResponse("/rest/summary/getTaskSummary?").then(function (response) {
            if (response != null) {
                $scope.taskSummary = response[0];
            }
        });
    };
    $scope.loadNotesData();

    // 小红点未读消息总条数提示
    RESTService.getResponse("/rest/chat/getUnreadCount?").then(function (response) {
        $scope.notes.count = ~~(response && response[0].count);
    });

    // go to bottom of message list
    function fixPageDisplay() {
        if (!$scope.if_open_chat || !$('.row-row>.cell')[0]) {
            return;
        }

        var timer = $timeout(function () {
            // $('.row-row>.cell').scrollTop(9999999);
            var div_scrollHeight = $('.row-row>.cell')[0].scrollHeight;
            $('.row-row>.cell').animate({scrollTop: div_scrollHeight}, 500);
            $timeout.cancel(timer);
        })
    }

    //消息发送者id
    // var userId = '';
    //消息接收者id
    var toId = '';
    var index = '';
    var delId, delInd;
    $scope.friendInfo = '';
    var websocket = null;
    var userMsgKeyList = [];
    var _access_token = AuthService.loadData("_access_token");
    $scope.userIdList = [];

    $scope.friendMsgs = [];
    $scope.choosenUserName = "";
    $scope.choosenUserId = "";
    $scope.choosenPic = "";

    // 上拉加载历史消息
    var topSize = 0;
    var n = 1;

    function loadToTop() {
        $('.cell').scroll(function () {
            topSize = $('.cell')[0].scrollTop;
            if (topSize == 0) {
                $scope.noMore = false;
                $scope.loadingHistory = true;
                getHistoryData()
            }
        });
    }

    function getHistoryData() {
        console.log('加載數據', $('.cell-inner')[0].scrollHeight);
        var before = $('.cell-inner')[0].scrollHeight;
        var topMsgId = $scope.friendMsgs;
        if ($scope.friendMsgs[0] == undefined) {
            $scope.loadingHistory = false;
            return;
        }
        var chatId = $scope.friendMsgs[0].id;
        console.log('chatId ============ ', chatId, $scope.friendMsgs[0]);
        RESTService.getResponse("/rest/chat/getFriendChats?friendId=" + toId + '&chat_Id=' + chatId).then(function (resp) {
            console.log(12345, resp);
            if (!resp[0]) {
                console.log('无更多数据');
                $scope.loadingHistory = false;
                $scope.noMore = true;
                return;
            }

            var m = 1;
            angular.forEach(resp[0].messages, function (thisArr) {
                thisArr.number = n + '-' + m++;
            });
            ++n;

            console.log(resp[0].messages[0]);
            $scope.loadingHistory = false;
            console.log('111111111111111111111111111111111111', resp[0].messages, $scope.friendMsgs);
            $scope.friendMsgs = $.merge(resp[0].messages, $scope.friendMsgs);
            // console.log('111111111111111111111111111111111111', $scope.friendMsgs);
            // create userMsgKeyList
            userMsgKeyList = [];
            angular.forEach($scope.friendMsgs, function (value) {
                var msgKey = (value.key != null && value.key != '') ? value.key : value.id;
                userMsgKeyList.push(msgKey);
            });
            console.log('新id列表 ======', userMsgKeyList);

            console.log($scope.friendMsgs.length, $scope.friendMsgs);
            $timeout(function () {
                console.log('加載數據', $('.cell-inner')[0].scrollHeight, $('.cell-inner')[0].scrollHeight - before);
                var newDomHeight = $('.cell-inner')[0].scrollHeight - before;
                $('.row-row>.cell').animate({scrollTop: newDomHeight - 25}, 0);
            });
        })
    }

    // 获取好友id列表
    RESTService.getResponse("/rest/chat/getChats?").then(function (response) {
        if (response.length <= 0) {
            return;
        }

        $scope.notes.list = response;
        // create userIdList
        $scope.userIdList = [];
        angular.forEach(response, function (value) {
            $scope.userIdList.push(value.userId);
        });

        console.log('好友id列表 ==== ', $scope.userIdList);
    });

    // console.log({
    //     '$rootScope.currentUser.userId---': $rootScope.currentUser.userId,
    //     '_access_token': _access_token,
    //     '$scope.currentUser.userId':$scope.currentUser.userId
    // });

    //打开聊天窗口
    $scope.openChat = function () {
        if (websocket == null) {
            ws();
        }

        $scope.if_open_chat = !$scope.if_open_chat;
        if ($scope.if_open_chat == false) {
            return;
        }

        //获取好友列表
        RESTService.getResponse("/rest/chat/getChats?").then(function (response) {
            console.log('好友列表', response);
            if (response.length <= 0) {
                return;
            }
            var test = response.length;
            console.log('好友列表002', test);

            $scope.notes.list = response;

            // create userIdList
            $scope.userIdList = [];
            angular.forEach(response, function (value) {
                $scope.userIdList.push(value.userId);
            });

            // first open window of chat
            if ($scope.friendId == undefined) {
                $scope.friendId = response[0].userId;
                $scope.friendInfo = response[0].user;
                index = 0;
            }

            $scope.loadFriendChats($scope.friendId, $scope.friendInfo, index);

        });

        $timeout(function () {
            console.log('再來一瓶');
            loadToTop();
        });

        $('[data-toggle="tooltip"]').tooltip();
    };

    //获取指定好友的消息列表
    $scope.loadFriendChats = function (oFriendId, oFriendInfo, ind) {
        $scope.noMore = false;
        $scope.loadingHistory = false;
        $scope.notes.ifShowMore = 0;
        n = 1;
        // clear userMsgKeyList
        userMsgKeyList = [];
        $scope.choosenUserName = $scope.notes.list[ind].userName;
        $scope.choosenUserId = $scope.notes.list[ind].userId;
        $scope.choosenPic = $scope.notes.list[ind].pic;

        toId = oFriendId;
        index = ind;
        delId = oFriendId;
        delInd = ind;
        $scope.friendInfo = oFriendInfo;

        console.log('toId:', toId);

        $scope.friendMsgs = [];
        $scope.friendId = toId;
        $scope.friendIndex = ind;
        RESTService.getResponse("/rest/chat/getFriendChats?friendId=" + toId).then(function (response) {

            console.log('消息列表--', response);

            if (response.length <= 0) {
                return;
            }

            $scope.currentYear = Date.parse(new Date().getFullYear() + "-01-01 00:00:00");
            $scope.currentDate = new Date(new Date().toLocaleDateString()).getTime();

            console.log(oFriendId, ind);
            $scope.friendMsgs = response[0].messages;


            // create userMsgKeyList
            angular.forEach(response[0].messages, function (value) {
                var msgKey = (value.key != null && value.key != '') ? value.key : value.id;
                userMsgKeyList.push(msgKey);
            });
            console.log('切换好友获取列表--', userMsgKeyList);
            console.log($scope.friendMsgs, 'friendMsgs');

            console.log('未读消息条数(改前)', {
                '总': $scope.notes.count,
                '当前': $scope.notes.list[ind].noReadMessages,
                index: ind,
                '$scope.notes.list': $scope.notes.list
            });

            // no read num 动作
            if ($scope.notes.list[ind].noReadMessages > 0) {
                // no read num of user on icon-bell
                $scope.notes.count = $scope.notes.count - $scope.notes.list[ind].noReadMessages;
                // no read num of sender at friends list
                $scope.notes.list[ind].noReadMessages = 0;
                console.log($scope.notes.list);
                console.log('未读消息条数(改后)', {
                    '总': $scope.notes.count,
                    '当前': $scope.notes.list[ind].noReadMessages
                });

                // 数据库消息未读改已读(已读不为0时执行)
                RESTService.postResponse("/rest/chat/setUnreadFlag?", {friendId: toId}).then(function (res) {
                    console.log('未读变已读', res);
                })
            }

            // go to bottom of message list
            fixPageDisplay();
            // console.log('消息列表$scope.friendMsgs：',$scope.friendMsgs);
        });

        // 此处应有写数据库操作，当消息请求完成后减少铃铛和对应好友的未读提示数字（页面和数据库）

    };

    // close window of message
    $scope.closeChat = function () {
        topSize = -10;
        $scope.if_open_chat = false;
        $scope.cnContent = '';
        $scope.notes.ifShowMore = false;
    };

    // 建立WebSocket连接
    ws();
    function ws() {
        if ('WebSocket' in window) {
            if (!_access_token) {
                console.log('error ========== system error');
                return;
            }
            var reconnectWS = '';
            $scope.notes.img = [];
            websocket = new WebSocket(CS.url + "access_token=" + _access_token);

            //当Browser和WebSocketServer连接成功后，会触发onopen消息;
            websocket.onopen = function (event) {
                console.log("连接已建立", websocket);
            }

            //如果连接失败，发送、接收数据失败或者处理数据出现错误，browser会触发onerror消息;
            websocket.onerror = function (e) {
                websocket.close();
                websocket = null;
                console.log("连接错误", e);
            };

            //当Browser接收到WebSocketServer端发送的关闭连接请求时，就会触发onclose消息
            websocket.onclose = function (e) {
                websocket = null;
                console.log("连接断开，10秒后将自动重连", e);
                reconnectWS = setTimeout(function () {
                    (websocket == null) ? ws() : clearTimeout(reconnectWS);
                }, 10000)
            };

            //当Browser接收到WebSocketServer发送过来的数据时，就会触发onmessage消息，参数evt中包含server传输过来的数据
            websocket.onmessage = function (e) {
                onMessage(e);
            };
        } else {
            alert("The browser don't support WebSocket， if you did not received message of online， please change browser as google chrome or 360 chrome.");
        }
    }

    function onMessage(e) {
        var json = JSON.parse(e.data);// new msg

        // is new message notify
        if (json.cnContent || json.enContent) {

            console.log('you have a new message === ', json);

            // 若聊天窗口未打开
            if ($scope.if_open_chat == false) {
                console.log(' 聊天窗口未打开');
                // 如果是未读消息，则铃铛+1
                if (json.read == false) {
                    console.log(' 是未读消息，铃铛+1');
                    $scope.notes.count += 1;
                }
            }
            // 若聊天窗口打开
            else {

                var otherId = json.userId == json.fromId ? json.toId : json.fromId;

                // 对方不在自己的好友列表中, ---> 重新获取好友列表
                if ($.inArray(otherId, $scope.userIdList) < 0) {
                    console.log('对方不在自己的好友列表中');
                    //获取好友列表
                    RESTService.getResponse("/rest/chat/getChats?").then(function (response) {
                        $scope.notes.list = response;

                        // create userIdList
                        $scope.userIdList = [];
                        angular.forEach(response, function (value) {
                            $scope.userIdList.push(value.userId);
                        });

                        // recive medical Msg
                        // console.log('=================================', $scope.friendId);
                        if (isMedicalMsg == true) {
                            isMedicalMsg == false;
                            $scope.friendId = response[0].userId;
                            $scope.friendInfo = response[0].user;
                            index = 0;
                            $scope.loadFriendChats($scope.friendId, $scope.friendInfo, index);
                            console.log('=================================---------------------------');
                        }
                    });

                    // 小红点未读消息总条数提示
                    RESTService.getResponse("/rest/chat/getUnreadCount?").then(function (response) {
                        $scope.notes.count = ~~(response && response[0].count);
                    });
                    return;
                }

                // 不在和otherId聊天,显示新消息提示
                if (toId != otherId) {
                    console.log('不在和otherId聊天,显示新消息提示');
                    // 如果是未读消息，则铃铛+1,对应好友未读+1
                    if (json.read == false) {
                        console.log('是未读消息，铃铛+1,对应好友未读+1');
                        // 铃铛+1
                        $scope.notes.count += 1;

                        // 对应好友未读+1
                        for (var i = 0; i < $scope.notes.list.length; i++) {
                            if ($scope.notes.list[i].userId == otherId) {
                                $scope.notes.list[i].noReadMessages += 1;
                                console.log('消息发送者的未读提示', $scope.notes.list[i].noReadMessages);
                                break;
                            }
                        }
                    }
                }
                // 在和otherId聊天，直接显示新消息
                else {
                    console.log('在和otherId聊天，直接显示新消息');
                    var msgKey = (json.key != null && json.key != '') ? json.key : json.id;
                    var newMsgIndex = $.inArray(msgKey, userMsgKeyList);

                    if (newMsgIndex < 0) {  // 添加消息
                        console.log('key不存在，添加', newMsgIndex);
                        // push user Msg Key
                        userMsgKeyList.push(msgKey);

                        // push message
                        $scope.friendMsgs.push(json);

                        // refresh data
                        $scope.$apply();

                        // go to bottom of message list
                        fixPageDisplay();
                    } else {                // 替换消息
                        console.log('key存在，替换', newMsgIndex);
                        $scope.friendMsgs[newMsgIndex] = json;
                    }

                    // 数据库消息未读改已读(已读不为0时执行)
                    RESTService.postResponse("/rest/chat/setUnreadFlag?", {friendId: toId}).then(function (res) {
                        console.log('未读变已读', res);
                    })
                }

            }

            // refresh data
            $scope.$apply();
        }
        // is online notify
        else {
            console.log('notice :: go live ---', json);
        }
    }

    //点击发送消息
    $scope.sendMessage = function (content,e) {
        var e = e||event
        e.stopPropagation();
        if(content){
            $scope.notes.content = content;
        }

        if (!$scope.notes.content) {
            $scope.notes.showQukMsgs = !$scope.notes.showQukMsgs;
            return;
        }

        if (websocket == null) {
            console.log('error ========== WebSocket is offline， please try again later！');
            ws();
            return;
        }

        var _msg = $scope.notes.content;
        $scope.notes.content = '';
        $scope.notes.showQukMsgs = false;

        // push massage
        var pushMsg = function (msg) {
            console.log('$scope.friendMsgs----', $scope.friendMsgs);
            $scope.friendMsgs.push({
                fromId: $scope.currentUser.userId,
                fromUserPic: $scope.currentUser.headImageUrl,
                cnContent: $sce.trustAsHtml(msg)
            });
        }

        // send message
        var send = function (msg) {
            var key = $.now() + toId.toString();
            console.log('发送key', key);
            userMsgKeyList.push(key);
            var mes = {
                toId: toId,
                content: msg,
                key: key
            };
            websocket.send(JSON.stringify(mes));
            console.log('success ========== message send success', mes);

            // this[key] = function(){
            //     console.log(key);
            // };
            // this[key]();
        };

        // show message
        pushMsg(_msg);

        // send message
        send(_msg);

        // go to bottom of message list
        fixPageDisplay();
    };

    //回车发送消息
    $('#sendMsg').keyup(function (e) {
        var e = e || event;
        if(e.keyCode == 13){
            if($scope.notes.content != "" && $scope.notes.content != null){
                $scope.sendMessage();
            }
        }
    });

    // 聊天窗口点击事件监听
    $scope.clickChatWindow = function(){
        if($scope.notes.showQukMsgs == true){
            $scope.notes.showQukMsgs = false;
        }
        if($scope.notes.ifShowMore == true){
            $scope.notes.ifShowMore = false;
        }
    }

    //加好友
    $scope.addFriends = function (userId) {
        RESTService.postResponse('/rest/chat/createChatMessageAddingFriend?', {friendId: userId})
            .then(function (response) {
                console.log(response);
                RESTService.pop('success', null, '加好友请求已发送', 1000);
                // $scope.cancel();
            });
    };

    //同意添加为好友
    $scope.chatAct = function (url) {
        RESTService.getResponse(url).then(function (response) {
            console.log(response);
        })
    };

    //删除好友
    $scope.openDeleteFriend = function (id, e, index) {
        var e = e || event;
        console.log('参数测试-----------', id, index, e);
        e.stopPropagation();
        delId = id;
        delInd = index;
        $('.prompt-del-frd').modal();
    };
    $scope.deleteFriend = function () {
        RESTService.getResponse('/rest/userfriend/deleteFriend?friendId=' + delId).then(function (response) {
            console.log(response);
            try {
                modalInstance.close();
            } catch (e) {
                console.log(e);
            }
            $('.prompt-del-frd').modal('hide');
            $scope.notes.list.splice(delInd, 1);
            $scope.userIdList.splice(delInd, 1);
            if (delId == toId) {
                $scope.loadFriendChats($scope.notes.list[0].userId, $scope.notes.list[0].user, 0);
            }
            delId = '';
            delInd = '';
        })
    }


    //浏览器关闭前请求断开ws服务器
    // window.onbeforeunload = function () {
    //     if (null != websocket) {
    //         websocket.close();
    //     }
    // };
    window.onunload = function () {
        if (null != websocket) {
            websocket.close();
        }
    };

    // clear chat messages of selected friend
    $scope.clearMessage = function () {
        RESTService.postResponse("/rest/chat/clearChatMessage?", {friendId: toId}).then(function (res) {
            if (res[0].result == true) {
                $('.model-clearMessage').modal('hide');
                $scope.friendMsgs = [];
                RESTService.pop('success', null, '消息列表已清空', 1000);
                console.log('system: message list been cleared!');
            }
        })
    }

    // sendPatient
    $scope.sendPatient = function (a, b) {
        console.log('sendPatient');
    }

    // sendImg
    $scope.sendImg = function (a, b) {
        console.log('sendImg');
    }

    // sendVioce
    $scope.sendVioce = function (a, b) {
        console.log('sendVioce');
    }

    // send medical Msg
    var isMedicalMsg = false;
    $scope.medicalMsg = function(Id){
        isMedicalMsg = true;
        RESTService.postResponse('/rest/chat/createChatMessageCS?',{friendId:Id}).then(function(res){
            modalInstance.close();
            console.log(res, modalInstance);
        });
    }

    RESTService.getResponse('/rest/chat/getSwiftMessages?').then(function(res){
        $scope.qukMsgList = $scope.locale == 'Cn' ? res[0] : res[1];
    })

    $scope.openQukMsg = function(e){
        var e = e || event;
        e.stopPropagation();
        $scope.notes.showQukMsgs = true;
        $scope.notes.ifShowMore = false;
    }
}

function chatCtrl($rootScope, $scope, $interval, $timeout, $filter, $translate, RESTService, CS) {
    $scope.notes = {
        list: []
    };
    // var timer = $interval(function(){
    //  $scope.loadNotesData();
    //  }, 1000 * 10);  //exec one time of 10 seconds
    // $scope.currentUser = $rootScope.currentUser;
    $scope.friendId = null;
    $scope.friendIndex = 0;

    //消息发送者id
    var userId = '';
    //消息接收者id
    var toUser = '';
    var websocket = null;

    $rootScope.loadMsg = function () {
        //打开消息时建立连接，若已建立，则不再重新建立
        if (websocket == null) {
            userId = $rootScope.currentUser.userId;
            ws();
        }
        $scope.loadNotesData();
    };

    $scope.loadNotesData = function () {

        //消息
        var firstUserId = null;
        RESTService.getResponse("/rest/chat/getChats?").then(function (response) {
            $scope.notes.list = [];
            angular.forEach(response, function (value) {
                if (firstUserId == null) {
                    firstUserId = value.userId;
                    toUser = value.userId;
                }
                this.push({
                    userId: value.userId,
                    userName: value.userName,
                    content: value.lastMessage.content,
                    uri: value.lastMessage.uri,
                    time: value.lastMessage.time,
                    pic: value.pic,
                    noReadMessages: value.noReadMessages
                });
            }, $scope.notes.list);
            console.log(1234, $scope.notes.list);
            if ($scope.friendId == null && firstUserId != null) {
                $scope.friendId = firstUserId;
                $scope.loadFriendChats($scope.friendId);
            }
        });
    };


    $scope.friendMsgs = [];
    $scope.choosenUserName = "";
    $scope.choosenUserId = "";
    $scope.choosenPic = "";
    $scope.loadFriendChats = function (friendId, index) {
        toUser = friendId;
        console.log('toUser:', toUser);

        $scope.content = "";
        $scope.friendMsgs = [];
        $scope.friendId = friendId;
        $scope.friendIndex = index;
        RESTService.getResponse("/rest/chat/getFriendChats?friendId=" + friendId).then(function (response) {
            angular.forEach(response, function (value) {
                $scope.choosenUserName = value.userName;
                $scope.choosenUserId = value.userId;
                $scope.choosenPic = value.pic;
                angular.forEach(value.messages, function (message) {
                    this.push({
                        userId: value.userId,
                        userName: value.userName,
                        content: message.content,
                        uri: message.uri,
                        time: message.time,
                        pic: value.pic,
                        noReadMessages: value.noReadMessages,
                        fromMe: message.fromMe,
                        read: message.read
                    });
                }, $scope.friendMsgs);
            });

            fixPageDisplay();
        });
    };

    $scope.visible = true;
    $scope.deleteCheck = function () {
        $scope.visible = false;
    };
    $scope.closeCheck = function () {
        $scope.visible = true;
    };

    $scope.deleteMessages = function (friendId) {
        if (friendId == null || friendId == "") return;
        $scope.visible = false;
        var url = "/rest/chat/clearChatMessage?";
        RESTService.postResponse(url, {friendId: friendId}, true).then(function (response) {
            if (response.code == 0) {
                //delete complete
                $scope.friendMsgs = [];
                $scope.friendId = null;
                $scope.choosenUserName = "";
                $scope.notes.list.splice($scope.friendIndex, 1);
            }
        });
    };

    //发送消息
    $scope.sendMessage = function () {
        alert(1);

        //检测消息服务是否连接正常，不正常则重新连接
        // if(websocket==null){
        //     ws();
        // }
        // console.log(websocket);

        //推送消息
        send()

        $scope.friendMsgs.push({
            pic: $scope.currentUser.headImageUrl,
            userId: $scope.currentUser.userId,
            // befUserId:$scope.friendMsgs.length-1,
            befUserId: $scope.friendMsgs[$scope.friendMsgs.length - 1].userId,
            content: $scope.content,
            noReadMessages: 1,
            read: true,
            time: $filter('date')($.now(), 'yyyy-MM-dd hh:mm:ss')
        });
        $scope.content = "";
        // console.log($scope.friendMsgs);

        fixPageDisplay();
    }

    //让消息列表默认到达最底部
    function fixPageDisplay() {
        var timer = $timeout(function () {
            // $('.row-row>.cell').scrollTop(9999999);
            var div_scrollHeight = $('.row-row>.cell')[0].scrollHeight;
            $('.row-row>.cell').animate({scrollTop: div_scrollHeight}, 500);
            $timeout.cancel(timer);
        })
    }

    $('#chat, .row-row>.cell').preventScrollBubble();


    //建立WebSocket连接
    function ws() {
        console.log('userId---', userId);
        if ('WebSocket' in window) {
            websocket = new WebSocket(CS.url + "id=" + userId);
            //连接成功建立的回调方法
            websocket.onopen = function (event) {
                console.log("websocket open");
            }
            //连接发生错误的回调方法
            websocket.onerror = function () {
                console.log("websocket error");
                console.log("登录失败");
            };
            //连接关闭的回调方法
            websocket.onclose = function () {
                console.log("websocket close");
            };
            //接收到消息的回调方法
            websocket.onmessage = function (e) {
                //收到的消息
                var json = JSON.parse(e.data);
                console.log(json);
                //如果自己好友列表无消息发送者，那么将其添加到好友列表中
                var j = 0;
                for (var i = 0; i < $scope.notes.list.length; i++) {
                    // console.log('数据检测', $scope.notes.list);
                    if ($scope.notes.list[i].userId == json.senderID) {
                        break;
                    } else {
                        j += 1;
                    }
                }
                if ($scope.notes.list.length == j) {

                    $scope.notes.list.unshift({
                        lastMessage: {
                            // chatType: null,
                            // content: '',
                            // fromId: '',
                            // fromMe: '',
                            // id: '',
                            // out_Process_Date: null,
                            // out_Process_Flag: false,
                            // out_Type: "app",
                            // out_Uri: "http://121.43.148.35/referral/app/index.html#/go?tmp=1&sref=app.query.servreqs&params={'like':'S-17010042'}&access_token=THISISATOKEN",
                            // read: true,
                            // time: "2017-02-15 15:28:59",
                            // toId: 5836,
                            // uri: "app.query.servreqs",
                            // userId: 5836
                        },
                        messages: null,
                        noReadMessages: 1,
                        pic: json.pic,
                        userId: json.senderID,
                        userName: json.senderName

                    });
                    $scope.$apply(function () {
                        console.log('好友列表更新了！');
                    });
                }

                //将消息显示在对应好友的消息列表里面,注意此处收到消息时自己是否已打开该好友的聊天窗口
                //一旦新消息在聊天窗口中显示过，那么标记为已读
                //如果当前未激活该消息发送者窗口，则显示右上角未读消息条数

                //如果当前该消息发送者的聊天窗口已激活，那么不显示右上角消息条数，直接将消息显示到聊天窗口中
                $scope.friendMsgs.push({
                    userId: json.senderID,
                    userName: json.senderName,
                    content: json.content,
                    // uri: message.uri,
                    time: json.time,
                    // pic: value.pic,
                    // noReadMessages: value.noReadMessages,
                    // fromMe: message.fromMe,
                    read: 1
                });
                $scope.$apply(function () {
                    fixPageDisplay();
                    console.log('消息列表更新了！');

                });

                // if((typeof json.to) == 'undefined'){
                //     var html = '<div  onclick="choose(this)">所有人</div>';
                //     for(var k in json){
                //         html+='<div  onclick="choose(this)">'+json[k]+'</div>';
                //     }
                //     document.getElementById("right_top").innerHTML=html;
                // }else{
                //     var record = document.getElementById("left_top");
                //     var html = '<div >'+json.from+' : '+json.content+'</div>';
                //     record.innerHTML+=html;
                // }
            };
        } else {
            alert("当前浏览器不支持即时消息，使用该功能请更换谷歌或其他浏览器！");
        }
    }

    //推送消息
    function send() {
        console.log('userId----', $scope.currentUser.userId);
        var mes = {
            pic: $scope.currentUser.headImageUrl,
            senderID: userId,
            senderName: $scope.currentUser.userName,
            // befUserId:$scope.friendMsgs.length-1,
            receiverId: toUser,
            content: $scope.content,
            noReadMessages: 1,
            read: true,
            time: $filter('date')($.now(), 'yyyy-MM-dd hh:mm:ss')
        };
        if (null != websocket) {
            websocket.send(JSON.stringify(mes));
        }
        console.log(mes);
    }

    window.onbeforeunload = function () {
        if (null != websocket) {
            websocket.close();
        }
    };


    // 即时消息

    // function myMsg() {
    //
    //     var userName;
    //     var toUser = "";
    //     var websocket = null;
    //
    //     function login() {
    //         if (!document.getElementById("user_name").checkValidity()) {
    //             return;
    //         }
    //         userName = document.getElementById("user_name").value;
    //         if (userName == "") {
    //             return;
    //         }
    //         ws();
    //     }
    //
    //     function choose(arg) {
    //         toUser = arg.innerHTML;
    //         document.getElementById("to").innerHTML = '发送给:[<span >' + toUser + '</span>]';
    //         if (toUser === '所有人') {
    //             toUser = '';
    //         }
    //     }
    //
    //     function ws() {
    //         if ('WebSocket' in window) {
    //             websocket = new WebSocket("ws://" + location.host + "/TestWebScoket/chat?id=" + userName);
    //             //连接成功建立的回调方法
    //             websocket.onopen = function (event) {
    //                 console.log("websocket open");
    //                 var opt = document.getElementById("right_bottom");
    //                 opt.innerHTML = '<input type="button" id="login" value="发送" onclick="send()" style="margin-top:50px" />';
    //             }
    //             //连接发生错误的回调方法
    //             websocket.onerror = function () {
    //                 console.log("websocket error");
    //                 alert("登录失败");
    //             };
    //             //连接关闭的回调方法
    //             websocket.onclose = function () {
    //                 console.log("websocket close");
    //                 var opt = document.getElementById("right_bottom");
    //                 opt.innerHTML = '<input type="text" id="user_name" placeholder="User Name" maxlength="10" required/><input type="button" id="login" onclick]="login()" value="登录"/>';
    //             };
    //             //接收到消息的回调方法
    //             websocket.onmessage = function (e) {
    //                 var json = JSON.parse(e.data);
    //                 if ((typeof json.to) == 'undefined') {
    //                     var html = '<div  onclick="choose(this)">所有人</div>';
    //                     for (var k in json) {
    //                         html += '<div  onclick="choose(this)">' + json[k] + '</div>';
    //                     }
    //                     document.getElementById("right_top").innerHTML = html;
    //                 } else {
    //                     var record = document.getElementById("left_top");
    //                     var html = '<div >' + json.from + ' : ' + json.content + '</div>';
    //                     record.innerHTML += html;
    //                 }
    //             };
    //         } else {
    //             alert("Not Support!");
    //         }
    //     }
    //
    //     window.onbeforeunload = function () {
    //         if (null != websocket) {
    //             websocket.close();
    //         }
    //     };
    //
    //     function send() {
    //         var mes = {
    //             pic: $scope.currentUser.headImageUrl,
    //             userId: userId,
    //             userName: $scope.currentUser.userName,
    //             // befUserId:$scope.friendMsgs.length-1,
    //             befUserId: toUser,
    //             content: $scope.content,
    //             noReadMessages: 1,
    //             read: true,
    //             time: $filter('date')($.now(), 'yyyy-MM-dd hh:mm:ss')
    //         };
    //         if (null != websocket) {
    //             websocket.send(JSON.stringify(mes));
    //         }
    //         var html = '<div >' + input.value + ' : ' + userName + '</div>';
    //         document.getElementById("left_top").innerHTML += html;
    //         input.innerHTML = '';
    //     }
    // }


}

function PatientSummaryController($scope, $rootScope, $interval, $translate, RESTService) {
    $scope.patientSummary = '';

    $scope.loadNotesData = function () {
        RESTService.getResponse("/rest/summary/getPatientSummary?").then(function (response) {
            //$scope.patientSummary = response[0];
        });
    };
    $scope.loadNotesData();
}

//function ServiceSummaryController($scope, $rootScope, $interval, $translate, RESTService) {
//    $scope.patientSummary = '';
//
//  $scope.loadNotesData = function() {
//      RESTService.getResponse("/rest/summary/getPatientSummary?").then(function(response) {
//          $scope.patientSummary = response[0];
//      });
//  };
//  $scope.loadNotesData();
//}

function DashboardSummaryController($scope, $rootScope, $interval, $translate, RESTService) {
    $scope.dashboardSummary = '';

    $scope.loadData = function () {
        RESTService.getResponse("/rest/summary/getDashboardSummary?").then(function (response) {
            $scope.dashboardSummary = response[0];
        });
    };
    $scope.loadData();
}

app.controller("ServReqFlowController", ["$scope", "$modal", "$timeout", "RESTService", "$stateParams",
    function ($scope, $modal, $timeout, RESTService, $stateParams) {
        if ($scope.selectLang != 'English') {
            $scope.styleFix = {
                'cursor': 'default',
                'min-width': '54px'
            }
        } else {
            $scope.styleFix = {
                'cursor': 'default',
                'min-width': '124px'
            }
        }

        $scope.ServReq = angular.extend({}, $scope.selected.item);

        $scope.patientPackage = "";

        $scope.service_Id = $stateParams.service_Id;

        //$scope.like = $stateParams.like;

        var loadServFlowData = function () {
            // fix parameter
            if ($scope.ServReq.servReq_Id === undefined) {
                $scope.ServReq.servReq_Id = '';
            }
            if ($scope.ServReq.patient_Id === undefined) {
                $scope.ServReq.patient_Id = '';
            }
            if ($scope.ServReq.patCase_Id === undefined) {
                $scope.ServReq.patCase_Id = '';
            }

            // if no servReq_Id, read patient info
            RESTService.getResponse("/rest/patient/getPatientPackage?patient_Id=" + $scope.ServReq.patient_Id +
                "&patCase_Id=" + $scope.ServReq.patCase_Id + "&servReq_Id=" + $scope.ServReq.servReq_Id)
                .then(function (response) {
                    $scope.patientPackage = response[0];
                    console.log('数据包', $scope.patientPackage);
                });
            RESTService.getResponse("/rest/diseasetype/getDiseaseTypeList?").then(function (response) {
                $scope.diseaseType = response;
            });
        };

        $scope.init = function () {
            loadServFlowData();
        };

        // open upload image window
        $scope.openShowImage = function (mediCase) {
            var modalInstance = $modal.open({
                backdrop: "static",
                templateUrl: 'ShowImage.html',
                controller: 'ModalInstanceCtrl',
                size: 'lg',
                resolve: {
                    items: function () {
                        return mediCase;
                    }
                }
            });
            modalInstance.result.then(function (userId) {
                //ok click
            }, function () {
                //cancel
            });
        };

        //3 open modal
        $scope.open = function (attrs, model) {
            //model.scope = $scope;
            var modalInstance = $modal.open(angular.extend({
                backdrop: "static",
                controller: "ModalInstanceCtrl",
                resolve: {
                    items: function () {
                        return [Object(model)];
                    }
                }
            }, attrs));
        };
    }]);

app.controller("UserDetailCtrl", ["$scope", "RESTService",
    function ($scope, RESTService) {
        $scope.user = angular.extend({}, $scope.selected.item);

        $scope.activityList = [];

        if ($scope.user._doctor == null) {
            $scope.user._doctor = {
                userId: '',
                doctQuali_Id: '',
                hosp_Id: '',
                dept_Id: '',
                doctor_Intro: '',
                fee_Recommend: 0,
                fee_Diag: 0,
                fee_Solution: 0,
                cost_Surgery: 0,
                fee_Surgery: 0
            }
        }

        $scope.page = {
            totalItems: 0,
            currentPage: 1,
            currentItems: 0,
            maxSize: 5,				//max size of pagination
            itemsPerPage: 10
        }

        $scope.getActivityList = function () {
            var params = {
                userId: $scope.user.userId,
                pageNo: 1,
                pageSize: 10
            };
            RESTService.getResponse("/rest/useractivity/getUserActivityList?" + $.param(params)).then(function (response) {
                $scope.activityList = response;
            });
        }

        $scope.getActivityList();

        function User(item) {
            var user = {
                userId: item.userId,
                realName: item.realName,
                mobile_Phone: item.mobile_Phone,
                email: item.email,
                icCardFile: item.icCardFile,
                icNo: item.icNo,
                gender: item.gender,
                race_Id: item.race_Id,
                age: item.age,
                location_Country: item.location_Country,
                location_Province: item.location_Province,
                location_City: item.location_City,
                location_County: item.location_County,
                location_Town: item.location_Town,
                location_Address: item.location_Address,
                marriage: item.marriage,
                telephone: item.telephone,
                emerg_Contact: item.emerg_Contact,
                emerg_Contact_Mobile: item.emerg_Contact_Mobile,
                photo_File: item.photo_File
            };
            return user;
        };
        function Doctor(item) {
            var doctor = {
                userId: item.userId,
                doctQuali_Id: item.doctQuali_Id,
                hosp_Id: item.hosp_Id,
                dept_Id: item.dept_Id,
                doctor_Intro: item.doctor_Intro,
                fee_Recommend: item.fee_Recommend,
                fee_Diag: item.fee_Diag,
                fee_Solution: item.fee_Solution,
                cost_Surgery: item.cost_Surgery,
                fee_Surgery: item.fee_Surgery
            };
            return doctor;
        };

        //获取好友列表
        $scope.isFriend = false;
        $scope.userId = $scope.user.userId;
        RESTService.getResponse("/rest/chat/getChats?").then(function (response) {
            $scope.userIdList = [];
            angular.forEach(response, function (value) {
                $scope.userIdList.push(value.userId);
            });
            if (!Array.value) {
                if ($.inArray($scope.userId, $scope.userIdList) < 0) {
                    $scope.isFriend = true;
                }
            }
            return $scope.isFriend;
        });

        //加好友
        $scope.addFriends = function (userId) {
            $scope.friendId = userId;
            var url = '/rest/chat/createChatMessageAddingFriend?';
            RESTService.postResponse(url, {friendId: $scope.friendId})
                .then(function (response) {
                    RESTService.pop('success', null, '加好友请求已发送', 1000);
                    $scope.cancel();
                });
        };
    }]);


/*

 app.controller('AnalysizerCtrl', ['$scope', '$timeout', '$window',
 function ($scope, $timeout, $window) {
 $scope.showData = false;
 $scope.isLoadingPIG = false;
 $scope.isLoadingUJ = false;
 $scope.isLoadingBoxSummary = false;
 $scope.LoadingData = function (index) {
 $scope.showData = true;
 var pigHeight = $(".analysisContainer")[1].children[1].scrollHeight;
 var ujHeight = $(".analysisContainer")[1].children[2].scrollHeight;
 var boxSummaryHeight = $(".analysisContainer")[1].children[3].scrollHeight;
 if (index == 0) {
 //$scope.reLoadData = true;
 pigHeight = 0;
 ujHeight = 0;
 $scope.gridOptions.data = null;
 }
 var showSummaryBox = function () {
 $scope.isLoadingBoxSummary = false;
 }
 var showUj = function () {
 $scope.isLoadingUJ = false;
 //$scope.isLoadingSummaryBox = true;
 //$timeout(showSummaryBox, 1000);
 }
 var showPig = function () {
 $scope.isLoadingPIG = false;
 //$scope.isLoadingUJ = false;
 //$timeout(showUj, 10000);
 }
 if (pigHeight == 0) {
 $scope.isLoadingPIG = true;
 $timeout(showPig, 1000);
 } else if (ujHeight == 0) {
 $scope.isLoadingUJ = true;
 $timeout(showUj, 1000);
 } else if (boxSummaryHeight == 0) {
 $scope.isLoadingBoxSummary = true;
 $timeout(showSummaryBox, 1000);
 }
 };
 }]
 ).directive('whenScrollEnd', function () {
 return function (scope, elm, attr) {
 var pageWindow = $(this);
 pageWindow.bind('scroll', function (et, ed, pb) {
 var winScrollTop = pageWindow.scrollTop();
 var winHeight = pageWindow.height();
 var maxScrollHeight = $(".analysisContainer")[1].scrollHeight;
 if ((winScrollTop + winHeight) > maxScrollHeight) {
 scope.$apply(attr.whenScrollEnd);
 }
 });
 }
 });


 <div class="analysisContainer" ng-show="showData" when-scroll-end="LoadingData()">
 <div id="b" ng-show="isLoadingPIG" style="width: 100%; text-align: center; z-index: 1">
 <h6 class="loading">
 <img src="~/Content/Images/loading2.gif" />
 Loading Win & Convert data...
 </h6>
 </div>
 <div id="a" ng-show="!isLoadingPIG">
 <img src="~/2016-03-16_152323.png" />
 </div>
 <div ng-show="!isLoadingUJ">
 <img src="~/2016-03-16_153347.png" />
 </div>
 <div ng-show="!isLoadingBoxSummary">
 <img src="~/2016-03-16_153404.png" />
 </div>
 </div>

 */
